import { sceneAssistant } from '../index';

const ColorNormal = '#ff0000';
const ColorPress = '#ffff00';


export class Point {
    private hover = false;
    private graphics: cc.Graphics | null = null;

    constructor(parent: cc.Node, name = '', callback: Function) {
        const node: cc.Node = new cc.Node(name);
        node.parent = parent;
        this.graphics = node.addComponent(cc.Graphics);
        node.on(cc.Node.EventType.MOUSE_ENTER, () => {
            this.hover = true;
            this._updateGraphics();
        });
        node.on(cc.Node.EventType.MOUSE_LEAVE, () => {
            this.hover = false;
            this._updateGraphics();
        });
        node.on(cc.Node.EventType.TOUCH_START, (event: cc.Event.EventTouch) => {
            event.stopPropagation();
            event.stopPropagationImmediate();
        });
        node.on(cc.Node.EventType.TOUCH_MOVE, (event: cc.Event.EventTouch) => {
            event.stopPropagation();
            event.stopPropagationImmediate();
            callback && callback(event);
        });
        node.on(cc.Node.EventType.MOUSE_DOWN, (event: cc.Event.EventMouse) => {
        });
        node.addComponent(cc.BlockInputEvents);
        this._updateGraphics();
    }

    _updateGraphics(): void {
        const colorString: string = this.hover ? ColorPress : ColorNormal;
        if (this.graphics) {
            this.graphics.clear();
            const color = cc.color();
            color.fromHEX(colorString);
            this.graphics.fillColor = color;
            this.graphics.fillRect(-this.PointWidth / 2, -this.PointHeight / 2, this.PointWidth, this.PointHeight);
            this.graphics.fill();
        }
    }

    visibleNode(b: boolean): void {
        const node = this.graphics?.node;
        if (node && node.isValid) {
            node.active = b;
        }
    }

    get PointWidth(): number {
        return 10 / sceneAssistant.scale;
    }

    get PointHeight(): number {
        return 10 / sceneAssistant.scale;
    }

    update(pos: cc.Vec2): void {
        this.graphics?.node?.setPosition(pos.x, pos.y);
        this.graphics?.node.setContentSize(this.PointWidth, this.PointHeight);
        this._updateGraphics();
    }
}
